package com.podmanager.UI;

import com.podmanager.data.*;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CursorAdapter;
import android.widget.FilterQueryProvider;
import android.widget.Spinner;

public class EpisodesFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
	private ImageCursorAdapter mListAdapter;
	private SimpleCursorAdapter  mSpinnerAdapter;
	private int prev_dropdown_position = -1;
	private Spinner episodes_filter_dropdown;
	private static final int SPINNER_LOADER_ID = 110;
	private static final int EPISODE_LOADER_ID = 200;

	public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.episodes_layout, container, false);
        setupSpinner(rootView);
    	setupListAdapter();

        return rootView;
    }


	private void setupSpinner(View view) {
    	episodes_filter_dropdown = (Spinner) view.findViewById(R.id.episodes_filter_dropdown);
    	
    	//ties spinner options to the podcasts available in subscription table
    	addSubscriptionsToFilter();

    	//setup to apply filter when a subscription is selected
    	episodes_filter_dropdown.setOnItemSelectedListener(new OnItemSelectedListener(){
			@Override
			public void onItemSelected(AdapterView<?> spinner, View view,
					int position, long id) {
				if(position == prev_dropdown_position)
					return;
				prev_dropdown_position = position;

				//second & third important steps to enable custom queries.  
				//Must call the filter, and must set adapter to apply it
				mListAdapter.getFilter().filter(""+(id==0?"":id));
				setListAdapter(mListAdapter);
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
    	});
    	
	}
	
	private void addSubscriptionsToFilter() {		
		String[] from = new String[]{PMDatabase.SUBSCRIPTIONS.SUB_TITLE};
		// create an array of the display item we want to bind our data to
		int[] to = new int[]{android.R.id.text1};
		// create simple cursor adapter
//		SimpleCursorAdapter adapter =
//		  new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
		mSpinnerAdapter =new SimpleCursorAdapter(this.getActivity(),
				android.R.layout.simple_spinner_item, null, from, to,
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		mSpinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
		episodes_filter_dropdown.setAdapter(mSpinnerAdapter);
		LoaderManager loaderManager = this.getLoaderManager();
		loaderManager.initLoader(SPINNER_LOADER_ID, null, this);
	}
	
	private void setupListAdapter() {		
		int[] viewIDs = new int[] { 
				R.id.episodes_item_date, 
				R.id.episodes_item_description, 
				R.id.episodes_item_image, 
				R.id.episodes_item_title, 
				R.id.episodes_item_playlist_button, 
				R.id.episodes_item_read_button, 
				R.id.episodes_item_download_button};		

		String[] columns = new String[] {
				PMDatabase.EPISODES.EPI_DATE,
				PMDatabase.EPISODES.EPI_DESCRIPTION,
				PMDatabase.EPISODES.EPI_IMAGE_PATH,
				PMDatabase.EPISODES.EPI_TITLE,
				PMDatabase.EPISODES.IS_IN_PLAYLIST,
				PMDatabase.EPISODES.IS_READ,
				PMDatabase.EPISODES.FILE_PATH};
				
		mListAdapter = new ImageCursorAdapter(this.getActivity(),
				R.layout.episodes_item_layout, null, columns, viewIDs,
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		// Initialize the Loader with id LOADER_ID, and this activity.
		// As the Loader sees changes in the data, these changes will be
		// reported back to this activity through the LoaderCallbacks interface
		setListAdapter(mListAdapter);
		LoaderManager loaderManager = this.getLoaderManager();
		loaderManager.initLoader(EPISODE_LOADER_ID, null, this);
		
		
		//important step to enable CUSTOM queries
		mListAdapter.setFilterQueryProvider(new FilterQueryProvider(){
						@Override
						public Cursor runQuery(CharSequence constraint) {
							String selection =null;
							if(constraint!=null && constraint !="")
								selection = PMDatabase.EPISODES.SUB_ROW_ID + "= "+constraint;
							String sort = PMDatabase.EPISODES.EPI_DATE +" desc";
							return getActivity().getContentResolver().query(
									Uri.withAppendedPath(DBContentProvider.EPISODES_URI, ""+constraint),
									PMDatabase.EPISODES.COLUMN_NAMES,	selection,	null,	sort);
						} 
					});
		setListAdapter(mListAdapter);
	}
	
	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		// We create the CursorLoader object here using the content URI. This
		// loader object will pull columns based on the PROJECTION.
		Loader<Cursor> returnValue=null;
		if (arg0==EPISODE_LOADER_ID)
		{
			String sort = PMDatabase.EPISODES.EPI_DATE+" desc";
			returnValue= new CursorLoader(this.getActivity(), DBContentProvider.EPISODES_URI,
				PMDatabase.EPISODES.COLUMN_NAMES, null, null, sort);	// here tpp
		}
		else if (arg0==SPINNER_LOADER_ID)
			returnValue= new CursorLoader(this.getActivity(), DBContentProvider.SUBSCRIPTION_SPINNER_URI,
					PMDatabase.SUBSCRIPTIONS.COLUMN_NAMES, null, null, null);
		return returnValue;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		switch(arg0.getId())
		{ 
		case SPINNER_LOADER_ID:
			mSpinnerAdapter.swapCursor(arg1);
			break;
		case EPISODE_LOADER_ID:
			try {
				mListAdapter.swapCursor(arg1);
			} catch (Exception e) 
				{ e.getMessage(); }
			break;
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		switch(arg0.getId())
		{ 
		case SPINNER_LOADER_ID:
			mSpinnerAdapter.swapCursor(null);
			break;
		case EPISODE_LOADER_ID:
			mListAdapter.swapCursor(null);
			break;
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		
		//kept getting weird "attempt to re-open an already-closed object: android.database.sqlite.SQLiteQuery" error
		//it was occuring whenever Fragment was re-created, so I'm destroying the loader
		this.getLoaderManager().destroyLoader(EPISODE_LOADER_ID);
	}
	
}
